#       FrontendFeedLibrary_test.py
#       
#       Copyright 2008 Joshua Scotton <josh@joshuascotton.com>
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

__licence__ = "GPLv2"
__copyright__ = "2008, Joshua Scotton"
__author__ = "Joshua Scotton <josh@joshuascotton.com>"

import unittest
import sys
import os

from pysqlite2 import dbapi2 as sqlite

sys.path += [os.path.abspath('..')]

from frontend.medialibrary.feeds import Feed, Entry, FeedLibrary
from frontend.backend_connection import BackendConnection

class MockBackendConnection(BackendConnection):
    def __init__(self): pass
    def close_connection(self): pass

class FrontendFeedLibraryTest(unittest.TestCase):
    """
    Tests the frontend.medialibrary.feeds.FeedLibrary object
    @todo comment tests
    @todo the test database doesn't seem to be working
    """

    def setUp(self):
        """Sets up everything for the test"""
        self.feed_db = os.path.abspath('.' + '/data/' + self.__str__() + '.db')
        if os.path.exists(self.feed_db):
            os.remove(self.feed_db) # Start fresh to avoid table creation error
        db_conn = sqlite.connect(self.feed_db)
        db_cursor = db_conn.cursor()
        db_cursor.execute("""CREATE TABLE feed(
                                url TEXT, 
                                title TEXT, 
                                subtitle TEXT, 
                                description TEXT, 
                                time TIME,
                                date DATE,
                                PRIMARY KEY(url))""")
                                
        db_cursor.execute("""CREATE TABLE entry(
                                feed_url TEXT,
                                title TEXT,
                                description TEXT,
                                isread TEXT,
                                time TIME,
                                date DATE,
                                id TEXT,
                                PRIMARY KEY(id))""")
        db_conn.commit()
        for i in range(10):
            feed_row = ("url"+str(i), 
                        "title"+str(i), 
                        "subtitle"+str(i), 
                        "description"+str(i),
                        "2008-01-01",
                        "12:00:00")
            db_cursor.execute("""INSERT INTO feed(url,title,subtitle,description,date,time) 
                                 VALUES (?,?,?,?,?,?)""", feed_row)
            db_conn.commit()
        for i in range(9):
            if i%2==0:
                read = "NO"
            else:
                read = "YES"
            entry_row = ("url2",
                         "entry"+str(i), 
                         "desc",
                         read,
                         str(i),
                         "2008-01-01",
                        "12:00:0"+str(i))
            db_cursor.execute("""INSERT INTO entry(feed_url,title,description,isread,id,date,time) 
                                 VALUES (?,?,?,?,?,?,?)""", entry_row)
            db_conn.commit()
        db_conn.close()
        
        try:
            self.backend_connection = MockBackendConnection()
        except:
            print "\nbackend_connection failed"
        self.library = FeedLibrary(self.backend_connection, self.feed_db)
        
    def tearDown(self):
        """
        Removes test database file
        """
        if os.path.exists(self.feed_db):
                os.remove(self.feed_db)

    def testAddFeed(self):
        """
        testAddFeed: This tests the add_feed function of the FeedLibrary
        """        
        #TODO testAddFeed needs writing
        pass
        
    def testRemoveFeed(self):
        """
        testRemoveFeed: Tests FeedLibrary.remove_feed()
        """
        self.library.remove_feed("url2")
        self.assertEqual(self.library.number_of_feeds(),9)
    
    def testIsEmptyWhenFull(self):
        """
        testIsEmptyWhenFull: Tests FeedLibrary.is_empty() when there are feeds in database
        """
        self.assertFalse(self.library.is_empty())
        
    def testIsEmptyWhenEmpty(self):
        """
        testIsEmptyWhenEmpty: Tests FeedLibrary.is_empty() when the feed list is empty
        """
        for i in range(10):
            self.library.remove_feed("url"+str(i))
        self.assertTrue(self.library.is_empty())
        
    def testGetFeeds(self):
        """
        testGetFeeds: Tests FeedLibrary.get_feeds() sorted by TITLE
        """
        feedlist = self.library.get_feeds('TITLE')
        for i in range(10):
            self.assertEqual(feedlist[i].get_feed_url(), "url"+str(i))
    
    def testGetFeedsByUnread(self):
        """
        testGetFeedsByUnread: Tests FeedLibrary.get_feeds() sorted by unread
        """
        feedlist = self.library.get_feeds('UNREAD')
        self.assertEqual(feedlist[0].get_feed_url(), "url2")
    
    def testGetLatestEntries(self):
        """
        testGetLatestEntries: Tests FeedLibrary.get_latest_entries()
        """
        latest = self.library.get_latest_entries(1)
        self.assertEqual("12:00:08", str(latest[0][1].get_time()))
      
    def testNumberOfFeeds(self):
        """
        testNumberOfFeeds: Tests FeedLibrary.number_of_feeds()
        """
        self.assertEqual(self.library.number_of_feeds(),10)
    
    def testNumberOfUnreadEntries(self):
        """
        testNumberOfUnreadEntries: Tests FeedLibrary.number_of_unread_entries()
        """
        self.assertEqual(self.library.number_of_unread_entries(),5)

    def testMarkAllAsRead(self):
        """
        testMarkAllAsRead: tests if all entries are marked as read
        """
        self.library.mark_all_as_read()
        self.assertEqual(self.library.number_of_unread_entries(),0)
        
